from flask import request, session
import requests
from bs4 import BeautifulSoup
import re
import json
from app.suse import suse
from model import Student
from db import db


# 抓取录取信息
@suse.route('/lq', methods=["GET"])
def get_lu_qu():
    ksh = request.args.get('ksh')
    if len(ksh) != 14:
        return json.dumps({'code': -1, 'msg': '考生号错了'})
    url = "http://lqcx.suse.edu.cn/showinfo.asp"
    payload = {
        "idnum": ksh,
        "bt1": "%CC%E1++%BD%BB"
    }
    r = requests.post(url, data=payload)
    r.encoding = "gbk"
    rs = r.text
    soup = BeautifulSoup(rs, "html.parser")
    a = soup.font
    c = a.find_all_next("b")
    del c[0:7]
    a = re.match(r'\D+(\d{13})(.*)', c[4].text, re.M | re.I)
    if a:
        rs = {
            'ksh': c[0].text,
            'name': c[1].text,
            'zy': c[2].text,
            'cc': c[3].text,
            'kd': a.group(1),
            'dz': a.group(2).lstrip()
        }
    else:
        rs = {
            'ksh': c[0].text,
            'name': c[1].text,
            'zy': c[2].text,
            'cc': c[3].text,
            'kd': '',
            'dz': c[4].text.lstrip()
        }
    return json.dumps(rs)


# 抓取班级信息
@suse.route('/bj', methods=["POST"])
def get_bj():
    username = request.values.get('username')
    password = request.values.get('password')
    rs = Student.query.filter_by(id_card=username).first()
    if rs:
        result = json.dumps({'code': 0, 'data': rs.to_json()})
        return result
    status = _jcc_login(username, password)
    if status == 2:
        status = _jcc_login(username, password)
    elif status == -1:
        headers = {
            'user-agent': 'bdspider'
        }
        url = "http://61.139.105.105:8088/Student/Detail"
        rs = requests.get(url, cookies=session.get('jcccookie'), headers=headers)
        rs.encoding = 'utf-8'
        rs = rs.text
        bs = BeautifulSoup(rs, 'html.parser')
        rs = bs.find_all('td')
        result = {
            "name": rs[1].text,
            "sex": rs[3].text,
            "nationality": rs[5].text,
            "year": rs[7].text,
            "xh": rs[9].text,
            "idCard": rs[11].text,
            "school": rs[13].text,
            "major": rs[15].text,
            "className": rs[17].text,
            "homeAddress": rs[19].text,
            "bankName": rs[21].text,
            "bankNumber": rs[23].text,
            "phone": rs[25].text,
            "email": rs[27].text,
            'qs': '',
            'ksh': ''
        }
        student = Student(result)
        db.session.add(student)
        db.session.commit()
        return json.dumps({'code': 0, 'data': result, 'msg': '查询成功'})
    elif status == 0:
        return json.dumps({'code': -1, 'msg': '应该是服务器炸了'})
    elif status == 1:
        return json.dumps({'code': -1, 'msg': '你输错账号密码了'})


# 模拟登录计财处
def _jcc_login(username, password):
    verify = requests.get('http://123.207.22.236:8080/jcc.jsp')
    rs = verify.json()
    if rs[0]:
        verifycode = rs[1]
        tmp = rs[2].split("=")
        cookies = {tmp[0]: tmp[1]}
        headers = {
            'user-agent': 'bdspider'
        }
        payload = dict()
        payload['UserName'] = username
        payload['Password'] = password
        payload['ValidateCode'] = verifycode
        rs = requests.post('http://61.139.105.105:8088/Account/LogOn?ReturnUrl=%2f',
                           data=payload, headers=headers, cookies=cookies, allow_redirects=False)
        if rs.status_code == 302:
            cookies['.ASPXAUTH'] = rs.cookies['.ASPXAUTH']
            session['jcccookie'] = cookies
            return -1
        elif rs.text.find("登录名称或密码不正确"):
            return 1
        elif rs.text.find("验证码错误"):
            return 2
        else:
            return 0
